package com.yloveg.controller;

import com.github.pagehelper.util.StringUtil;
import com.yloveg.base.BaseController;
import com.yloveg.base.Md5Util;
import com.yloveg.base.MyException;
import com.yloveg.common.DateUtil;
import com.yloveg.common.FreemarkUtil.MailType;
import com.yloveg.common.IpUtil;
import com.yloveg.common.NumUtil;
import com.yloveg.common.ValidateCode;
import com.yloveg.entity.LoginLog;
import com.yloveg.entity.SUserRole;
import com.yloveg.entity.SendMail;
import com.yloveg.entity.ShopInfo;
import com.yloveg.entity.Suser;
import com.yloveg.entity.Suser;
import com.yloveg.service.LoginLogService;
import com.yloveg.service.MailUtil;
import com.yloveg.service.SUserRoleService;
import com.yloveg.service.SendMailService;
import com.yloveg.service.ShopInfoService;
import com.yloveg.service.UserService;

import freemarker.template.TemplateException;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/user")
public class LoginController extends BaseController {
    private final Logger logger = Logger.getLogger(this.getClass());
    
    @Value("#{system.default_role}")
	private String default_role;
    
    @Autowired
    private UserService UserService;
    
    @Autowired
    private LoginLogService loginLogService;
    
    @Autowired
    private MailUtil mailUtil;
    
    @Autowired
    private ShopInfoService shopInfoService;
    
    @Autowired
    private SUserRoleService sUserRoleService;
    
    @Autowired
    private SendMailService sendMailService;

    
    @RequestMapping("/login")
    public String login(){
        return "user/login";
    }
    
    @RequestMapping("/forgetPwd")
    public String forgetPwd(){
        return "user/forgetPwd";
    }
    
    /*@RequestMapping("/register")
    public String register(){
        return "user/register";
    }*/

    @RequestMapping("/doLogin")
    @ResponseBody
    public Map<String, Object> doLogin(String code,Suser user, String remPwd,HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashedMap<String, Object>();
        
        logger.info("登录:" + user.getUsername() + ":" + user.getPassword());
        HttpSession session = request.getSession();
		String sessionCode = (String) session.getAttribute("code");
		if (!StringUtils.equalsIgnoreCase(code, sessionCode)) {  //忽略验证码大小写
			map.put("code", "2");
			map.put("msg", "验证码错误");
		}else{
			Map<String,Object> usrMap = new HashMap<String, Object>();
			usrMap.put("username", user.getUsername());
			usrMap.put("type", "1");
			List<Suser> listUser = UserService.selectByMap(usrMap);
			Suser admin = new Suser();
			if(listUser.size()>0){
				admin = listUser.get(0);
			}else{
				admin=null;
			}
	        if(null != admin){
	        	if(admin.getState()==0){
	        		map.put("code", "2");
	            	map.put("msg", "账号被冻结，请联系管理员");
	            	return map;
	        	}
	        }
	        if ((null != admin) && admin.getPassword().equals(Md5Util.encode(user.getPassword()))) {
	            setSessionUser(admin);
	            setCookieUser(user.getUsername(), user.getPassword(), remPwd,
	                response);
	            map.put("code", "1");
	            map.put("msg", "登录成功");
	            //店铺信息
	        	ShopInfo info = new ShopInfo();
	        	setSessionShop(info);
	        	info.setUserId(getSessionUser().getId());
	        	info = shopInfoService.queryOneShopInfo(info);
	        	if(info!=null){
	        		setSessionShop(info);	
	        	}
	            LoginLog log = new LoginLog();
	            log.setContent("登录系统");
	            log.setUserName(user.getUsername());
	            log.setUserIp(IpUtil.getLocalIp(request));
	            log.setState(1);
	            log.setCreateDate(new Date());
	            loginLogService.insertUserLog(log);
	        } else{
	            map.put("code", "0");
	            map.put("msg", "账号或密码错误");
	        }			
		}
        return map;
    }

    /*@RequestMapping("/doRegister")
    @ResponseBody
    public Map<String, Object> doRegister(Suser user, String code,HttpServletRequest request, HttpServletResponse response)throws MyException, IOException, TemplateException {
        Map<String, Object> map = new HashedMap<String, Object>();
        HttpSession session = request.getSession();
		String sessionCode = (String) session.getAttribute("code");
		logger.info("注册:" + user.getUsername() + ":" + user.getPassword()+",code:"+code+",sessionCode="+sessionCode);
		if (!StringUtils.equalsIgnoreCase(code, sessionCode)) {  //忽略验证码大小写
			map.put("code", "2");
			map.put("msg", "验证码错误");
		}else {
			Map<String,Object> usrMap = new HashMap<String, Object>();
			usrMap.put("username", user.getUsername());
			usrMap.put("type", "1");
			List<Suser> listUser = UserService.selectByMap(usrMap);
			Suser admin = new Suser();
			if(listUser.size()>0){
				admin = listUser.get(0);
			}else{
				admin=null;
			}
			if(admin!=null) {
				map.put("code", "0");
				map.put("msg", "该用户已经存在！");	
			}else {
				user.setPassword(Md5Util.encode(user.getPassword()));
				user.setType("1");
				int id = UserService.registerUser(user);
				if(id>0) {
					//自动加入默认角色
					Suser newUser = UserService.findUserByNameAndPassword(user.getUsername());
					SUserRole sUserRole = new SUserRole();
					sUserRole.setRoleId(Long.valueOf(default_role));
					sUserRole.setUserId(newUser.getId());
					sUserRoleService.insertSRole(sUserRole);
					//发送邮件
		            Map<String, Object> templateMap = new HashMap<String, Object>();
		            templateMap.put("username", user.getUsername());
		            templateMap.put("adminemail","582182099@qq.com");
		            templateMap.put("time", new Date());
		            mailUtil.sendTemplateMail(templateMap,"注册成功", "registerSuccess.ftl", user.getUsername(),MailType.REGISTER.getValue());
					map.put("code", "1");
					map.put("msg", "注册成功");
				}else {
					map.put("code", "0");
					map.put("msg", "注册错误请联系管理员！");				
				}				
			}
		}
        return map;
    }*/
    
    
    
	/**
	 * 响应验证码页面
	 * @return
	 */
	@RequestMapping(value="/validateCode")
	public String validateCode(HttpServletRequest request,HttpServletResponse response) throws Exception{
		// 设置响应的类型格式为图片格式
		response.setContentType("image/jpeg");
		//禁止图像缓存。
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
 
		HttpSession session = request.getSession();
 
		ValidateCode vCode = new ValidateCode(120,40,4,100);
		session.setAttribute("code", vCode.getCode());
		vCode.write(response.getOutputStream());
		return null;
	}
    public void setCookieUser(String userName, String password,
        String remberPwd, HttpServletResponse response) {
        /* 将用户名密码保存在cookie中 */
        if ("true".equals(remberPwd)) {
            Cookie cookieUser = new Cookie("cookie_user",
                    userName + "-" + password);
            /* 设定有效时间 以秒(s)为单位 */
            cookieUser.setMaxAge(7 * 24 * 60 * 60);
            /* 设置Cookie路径和域名 */
            cookieUser.setPath("/");
            response.addCookie(cookieUser);
        } else {
            Cookie cookieUser = new Cookie("cookie_user", null);
            /* 设定有效时间 以秒(s)为单位 */
            cookieUser.setMaxAge(0);
            /* 设置Cookie路径和域名 */
            cookieUser.setPath("/");
            response.addCookie(cookieUser);
        }
    }

    public static void main(String[] args) {
        System.out.println(Md5Util.encode("123456"));
        System.out.println("true".equals(null));
    }
    
    @RequestMapping("/signOut")
    public String SignOut(HttpServletRequest request, HttpServletResponse response){
    	System.out.println("用户退出了");
    	Suser user = this.getSessionUser();
    	if(user!=null){
            LoginLog log = new LoginLog();
            log.setContent("退出系统");
            log.setUserName(user.getUsername());
            log.setUserIp(IpUtil.getLocalIp(request));
            log.setState(1);
            log.setCreateDate(new Date());
            loginLogService.insertUserLog(log);
            request.getSession().removeAttribute(BaseController.SESSION_USER);    		
    	}
    	return "user/login";
    }
    
    /**
	 * @todo 用户登录
	 * @since 获取当前用户，
	 * 判断用户是否已经认证登录，
	 * 用账号密码创建UsernamePasswordToken，
	 * 调用subject的login方法
	 * @param
	 * @return
	 */
	@RequestMapping(value = "logon")
	public String logon(Suser user){
		//创建Subject实例对象
		Subject currentUser = SecurityUtils.getSubject();
		//判断当前用户是否已登录
		if(currentUser.isAuthenticated() == false){
			UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
			try {
				currentUser.login(token);
			} catch (AuthenticationException e) {
				e.getMessage();
				e.printStackTrace();
				System.out.println("登录失败");
				return "logon";
			}
		}
		return "index";
	}
	
    /**
	 * @todo 发送验证码
	 * @param
	 * @return
     * @throws TemplateException 
     * @throws IOException 
	 */
	@RequestMapping(value = "sendMailCode")
    @ResponseBody
    public Map<String, Object> sendMailCode(String userName) throws IOException, TemplateException{
		Map<String, Object> map = new HashedMap<String, Object>();
		if(StringUtil.isEmpty(userName)) {
			map.put("code", "0");
			map.put("msg", "邮箱不能为空");
		}else {
			Map<String,Object> usrMap = new HashMap<String, Object>();
			usrMap.put("username", userName);
			usrMap.put("type", "1");
			List<Suser> listUser = UserService.selectByMap(usrMap);	
			if(listUser.size()<1) {
				map.put("code", "0");
				map.put("msg", "不存在该用户");				
			}else {
				//发送邮件
	            Map<String, Object> templateMap = new HashMap<String, Object>();
	            templateMap.put("username", userName);
	            templateMap.put("adminemail","582182099@qq.com");
	            templateMap.put("time", new Date());
	            templateMap.put("code",NumUtil.getNum(6));
	            mailUtil.sendTemplateMail(templateMap,"BDY验证码", "mailCode.ftl", userName,MailType.FORGET_PWD.getValue());
				map.put("code", "1");
				map.put("msg", "验证码发送成功，请及时到邮箱查看");	
			}
		}

		return map;
	}
	
	/**
	 * @todo 保存修改密码
	 * @param
	 * @return
     * @throws TemplateException 
     * @throws IOException 
	 */
	@RequestMapping(value = "savePwd")
    @ResponseBody
    public Map<String, Object> savePwd(String code,Suser user) throws IOException, TemplateException{
		Map<String, Object> map = new HashedMap<String, Object>();
		if(StringUtil.isEmpty(user.getUsername())) {
			map.put("code", "0");
			map.put("msg", "邮箱不能为空");
			return map;
		}
		SendMail mail = new SendMail();
		mail.setMailContent(code);
		mail.setToMail(user.getUsername());
		mail = sendMailService.queryOneSendMail(mail);
		if(mail==null) {
			map.put("code", "0");
			map.put("msg", "验证码错误，请重新输入");	
		}else {
			Long time = DateUtil.getDatePoor(new Date(),mail.getCreateDate());
			if(time>10) {
				map.put("code", "0");
				map.put("msg", "验证码已经过时，请重新获取！");	
				return map;
			}
			Map<String,Object> usrMap = new HashMap<String, Object>();
			usrMap.put("username", mail.getToMail());
			usrMap.put("type", "1");
			List<Suser> listUser = UserService.selectByMap(usrMap);	
			if(listUser.size()<1) {
				map.put("code", "0");
				map.put("msg", "不存在该用户");	
			}else {
				Suser userTemp = listUser.get(0);
				userTemp.setPassword(Md5Util.encode(user.getPassword()));
				UserService.updateByPrimaryKeySelective(userTemp);
				map.put("code", "1");
				map.put("msg", "修改成功，请用新密码登录");	
			}
		}
		
		return map;
	}
	
}
